package club.beimeng.On2.BubbleSort;

import java.util.Arrays;

public class BubbleSort {

    public static void sort1(int[] nums){
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - 1 - i; j++) {
                if (nums[j] > nums[j+1]){
                    swap(nums,j,j+1);
                }
            }
        }
    }

    /**
     * 如果数组有序了，直接退出循环
     * @param nums
     */
    public static void sort2(int[] nums){
        boolean noSwap = false;
        for (int i = 0; i < nums.length - 1; i++) {
            if (noSwap)break;
            noSwap = true;
            for (int j = 0; j < nums.length - 1 - i; j++) {
                if (nums[j] > nums[j+1]){
                    swap(nums,j,j+1);
                    noSwap = false;
                }
            }
        }
    }

    public static void sort3(int[] nums){
        boolean noSwap = false;
        int lastIndex = nums.length-1;// 最后一个有序元素
        int swappedIndex = -1; // 上次交换位置
        while (!noSwap){
            noSwap = true;
            for (int i=0;i<lastIndex;i++){
                if (nums[i] > nums[i+1]){
                    swap(nums,i,i+1);
                    noSwap = false;
                    swappedIndex = i;
                }
            }
            lastIndex = swappedIndex;
        }
    }

    public static void swap(int[] nums,int a,int b){
        //初级方法
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }


    public static void main(String[] args) {
        int[] nums = {9,1,23,5,6,73,2,5,7,8,10,0};
        int[] nums2 = {1,2,3,4,5,6,7,8,9};
        BubbleSort.sort3(nums2);
        BubbleSort.sort3(nums);
        System.out.println(Arrays.toString(nums));
    }
}
